import {Component, Input, OnInit} from '@angular/core';
import {LocalDataSource, ViewCell} from 'ng2-smart-table';
import {SmartTableData} from '../../@core/data/smart-table';
import {ActivatedRoute} from "@angular/router";
import {NbDialogService} from "@nebular/theme";
import {CommonFormDialog} from "../../utils/CommonFormDialog";
import {AdminService} from "../../AdminService";
import {DevService, DocService} from "../../energy/api";
import {DeviceInfo} from "../../energy/api/model/deviceInfo";
import {BaseRequest} from "../../utils/BaseRequest";
import {map} from "rxjs/operators";
import {ResponseUnitInfo} from "../../energy/api/model/responseUnitInfo";
import {ResponseDeviceInfo} from "../../energy/api/model/responseDeviceInfo";

@Component({
  selector: 'ngx-smart-table',
  templateUrl: './device-document.component.html',
  styles: [`
    nb-card {
      transform: translate3d(0, 0, 0);
    }
    button {
      margin-top: 5px;
      margin-bottom: 5px;
      margin-right: 10px;
    }
    .margin {
      margin: 10px;
    }
  `],
})
export class DeviceDocumentComponent implements OnInit{
  settings = {
    pager:{
      display:true,
      perPage: 20
    },
    hideSubHeader: true,
    actions: {
      add: false,
      columnTitle: '操作',
      position: 'right',
    },
    edit: {
      editButtonContent: '<i class="nb-edit"></i>',
      saveButtonContent: '<i class="nb-checkmark"></i>',
      cancelButtonContent: '<i class="nb-close"></i>',
      confirmSave: true,
    },
    delete: {
      deleteButtonContent: '<i class="nb-trash"></i>',
      confirmDelete: true,
    },
    columns: {
      devNo: {
        title: '编号',
        type: 'custom',
        renderComponent: DeviceLinkRender
      },
      devName: {
        title: '设备名称',
        type: 'string',
      },
      devType: {
        title: '设备类型',
        type: 'string',
      },
      isPooled: {
        title: '是否公摊',
        type: 'string',
      },
      usesType: {
        title: '使用类型',
        type: 'string',
      },
      createDate: {
        title: '创建日期',
        type: 'string',
      },
      enableDate: {
        title: '启用日期',
        type: 'string',
      },
      devStatus: {
        title: '设备状态',
        type: 'string',
      },
      runStatus: {
        title: '运行状态',
        type: 'string',
      },
      devCode: {
        title: '设备代号',
        type: 'string',
      },
      devSerialNo: {
        title: '设备序列号',
        type: 'string',
      },
      devIp: {
        title: '设备IP',
        type: 'string',
      },
      devMac: {
        title: '设备MAC',
        type: 'string',
      },
      devAddr: {
        title: '设备地址',
        type: 'string',
      },
      devAdmin: {
        title: '设备管理员',
        type: 'string',
      },
      devAdminPhoneNo: {
        title: '管理员联系电话',
        type: 'string',
      },
      extInfo: {
        title: '额外信息',
        type: 'string',
      },
    },
  };
  source: DataDataSource;
  ud?:number=null;
  devNo:string = '';
  devName: string = '';
  devType: string = '';
  constructor(private service: SmartTableData
              ,private api:DevService
              ,private route: ActivatedRoute
              ,private dialogService: NbDialogService
              ,private admin:AdminService) {
  }

  ngOnInit(): void {
    this.route.paramMap.subscribe(value=>{
      const ud = value.get("unitId");
      if(ud!=null) this.ud = Number(ud);
      console.log(this.ud);
      this.source  = new DataDataSource(this.api,this.ud);
    });

  }

  filter(){
    this.source.devNo = this.devNo;
    this.source.devName = this.devName;
    this.source.devType = this.devType;
    this.source.setPage(1);
    this.source.refresh();
  }

  openAddPrompt() {
    const keys = Object.keys(this.settings.columns).filter(k => {
      return (this.settings.columns[k]['type'] == 'string'
        || this.settings.columns[k]['type'] == 'number')
        && this.settings.columns[k]['title'] != 'ID'
        && !k.endsWith("Date")
        && !k.endsWith("Status")
    });
    const columns = keys.filter(k=>{
      return k!='enableDate' && k!='devStatus' && k!='runStatus' && k!='createDate';
    }).map(k => {
      if(k=='isPooled'){
        return {title:this.settings.columns[k]['title'],type:'checkbox'};
      }
      if(k == 'devType'){
        return {title:this.settings.columns[k]['title'],type:'select',ext:[{title:'三相电表',value:'0'},{title:'智能电表',value:'1'}]};
      }
      return {title:this.settings.columns[k]['title'],type:'input'};
    }).sort((a,b)=>{
      let x;
      let y;
      switch (a.type) {
        case 'input':
          x = 1;
          break;
        case 'checkbox':
          x = 0;
          break;
      }
      switch (b.type) {
        case 'input':
          y = 1;
          break;
        case 'checkbox':
          y = 0;
          break;
      }
      return y-x;
    });
    this.dialogService.open(CommonFormDialog, {
      context:{
        data:columns,
        title: '新建设备'
      }
    }).onClose.subscribe(results=>{
      const data = <DeviceInfo>{};
      keys.forEach((k, i) => {
        if (columns[i]['type'] == 'number') {
          data[k] = Number(results[i]);
        } else {
          data[k] = results[i];
        }
      });
      data['operateType'] = "0";
      delete data['unitId'];
      this.api.postECADeviceInfo(new BaseRequest([data])).toPromise().then(response => {
        console.log(response);
        this.source.refresh();
      })
    })
  }


  onDeleteConfirm(event): void {
    if (window.confirm('Are you sure you want to delete?')) {
      this.api.postECADeviceInfo(new BaseRequest(
        [{
          operateType:"2",
          devNo:event.data['devNo'],
        }]
    )).toPromise().then(res=>{
        if(res.success){
          event.confirm.resolve();
        }else{
          event.confirm.reject();
        }
      }).catch(e=>{
        event.confirm.reject();
      });
      event.confirm.resolve();
    } else {
      event.confirm.reject();
    }
  }

  onEditConfirm(event):void {
    const newData = event.newData;
    newData['operateType']="1";
    this.api.postECADeviceInfo(new BaseRequest([newData])).toPromise().then(response=>{
      console.log(response);
      event.confirm.resolve();
    }).catch(e=>{
      console.log(e);
      event.confirm.reject();
    })
  }
}

export class DataDataSource extends LocalDataSource {
  devNo:string = '';
  devName: string = '';
  devType: string = '';
  all: number = -1;
  constructor(private api: DevService,private unitId?:number) {
    super()
  }

  count(): number {
    return this.all;
  }

  getElements(): Promise<any> {
    const query = {
      pageIndex: (this.pagingConf['page'] - 1) * this.pagingConf['perPage'],
      pageSize: this.pagingConf['perPage'],
      unitId: this.unitId
    };
    if(this.devNo!='') query['devNo'] = this.devNo;
    if(this.devName!='') query['devName'] = this.devName;
    if(this.devType!='') query['devType'] = this.devType;
    return this.api.postECAGetDeviceInfo(new BaseRequest(query)).pipe(map((res:ResponseDeviceInfo)=>{
      this.all = res.dataCount;
      return res.data;
    })).toPromise();
  }
}

@Component({
  template: `
      <a [routerLink]="'/pages/dev/detail/'+value">{{renderValue}}</a>
  `,
})
export class DeviceLinkRender implements ViewCell, OnInit {

  renderValue: string;

  @Input() value: string | number;
  @Input() rowData: any;

  ngOnInit() {
    this.renderValue = this.value.toString().toUpperCase();
  }

}
